package com.yanqu.road.web.controller.usercenter;


import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eUpdateLevel;
import com.yanqu.road.entity.servercenter.*;
import com.yanqu.road.entity.web.HttpGameWebParam;
import com.yanqu.road.server.manger.HotPackVersionMgr;
import com.yanqu.road.server.manger.PackageVersionMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.web.controller.BaseGameHttpServlet;
import com.yanqu.road.web.controller.usercenter.logic.ServerListHelper;
import com.yanqu.road.web.util.IpAddressHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@WebServlet(urlPatterns = "/packageUpdate")
public class PackageUpdate extends BaseGameHttpServlet {

	private static Logger logger = LogManager.getLogger(PackageUpdate.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/**
		 * 参数解析
		 */
		logger.info("request packageUpdate");
		HttpGameWebParam httpGameWebParam = super.parseRequest(request);
		JSONObject paramObj = httpGameWebParam.getParamObj();
		String param = httpGameWebParam.getParam();
		String language = httpGameWebParam.getLanguage();


		String openId;
		String serverId;
		String platformUserId;
		String packageVersion;
		String packageMark;
		String hotPackVersion;
		try {
			openId = paramObj.getString("openId");
			serverId = paramObj.getString("serverId");
			platformUserId = paramObj.getString("platformUserId");
			packageVersion = paramObj.getString("packageVersion");
			packageMark = paramObj.getString("packageMark");
			hotPackVersion = paramObj.getString("hotPackVersion");
		} catch (Exception e) {
			sendMessage(response, getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
			logger.error("packageUpdate request json格式出错！ json 字符串param为{}", param, e);
			return;
		}

		String ip = IpAddressHelper.getIpAddr(request);
		boolean isWhiteUser = ServerListMgr.isWhiteUser(ip, false, platformUserId);

		int forwardServer = 0;
        String appId = "";
		try {
			appId = paramObj.getString("appId");
			if (appId != null) {
				AppIdChaneelInfo appIdChaneelInfo = ServerListMgr.getAppIdChaneelInfo(appId);
				if (appIdChaneelInfo != null) {
					forwardServer = appIdChaneelInfo.getForwardServer();
				}
			}
		} catch (Exception e) {
			logger.error("appid is null json 字符串param为{}", param, e);
		}

		PackageMark packageMarkData = PackageVersionMgr.getPackageMark(packageMark);
		if(null == packageMarkData){
			sendMessage(response, getResultObj(GameErrorCode.E_PACKAGE_MARK_NO_FOUND, language).toJSONString());
			logger.error("packageUpdate packageMark no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
			return;
		}

		boolean needOldDeal = ServerListHelper.isNeedOldDeal(packageMark, isWhiteUser, forwardServer);
		if(needOldDeal){
		    oldDeal(response, packageMark, packageVersion, hotPackVersion, isWhiteUser, forwardServer, packageMarkData, language, appId);
        }else {
		    newDeal(response, packageMark, packageVersion, hotPackVersion, isWhiteUser, forwardServer, packageMarkData, language, appId);
        }
	}

	private void newDeal(HttpServletResponse response, String packageMark, String packageVersion, String hotPackVersion, boolean isWhiteUser,
                         int forwardServer, PackageMark packageMarkData, String language, String appId){
        PackageUpdateInfo packageUpdateInfo = PackageVersionMgr.getPackageUpdateInfo(packageMark, packageVersion, isWhiteUser, forwardServer);
        //整包更新级别
        JSONObject resultObj = getResultObj(0, language);
        int updateLevel = eUpdateLevel.Default.getValue();
        if(null != packageUpdateInfo){
            updateLevel = packageUpdateInfo.getUpdateLevel();
        }
        resultObj.put("updateLevel", updateLevel);
        //如果需要更新
        if(updateLevel == eUpdateLevel.Suggest.getValue() || updateLevel == eUpdateLevel.Force.getValue()){
            //推荐更新版本信息
            resultObj.put("updateMethod", packageUpdateInfo.getUpdateMethod());
            resultObj.put("updateUrl", packageUpdateInfo.getDownloadUrl());
        }

        //获取热更包信息
        boolean isReview = false;
        int hotPackUpdateLevel = eUpdateLevel.Default.getValue();
        String hotPackUpdateVersion = "";
        HotfixVersion currHotPackVersion = HotPackVersionMgr.getHotfixVersion(packageMark, packageVersion, hotPackVersion, isWhiteUser, forwardServer);
        if(null != currHotPackVersion){
            isReview = HotPackVersionMgr.isHotfixVersionReview(currHotPackVersion, appId, packageMarkData.getChannelId());
            hotPackUpdateLevel = currHotPackVersion.getUpdateLevel();
            hotPackUpdateVersion = currHotPackVersion.getUpdateVersion();
        }else {
            HotfixUpdateInfo hotfixUpdateInfo = HotPackVersionMgr.getHotfixUpdateInfo(packageMark);
            if(null != hotfixUpdateInfo){
                if(isWhiteUser){
                    if(!Objects.equals(hotfixUpdateInfo.getWhiteUpdateVersion(), hotPackVersion)) {
                        hotPackUpdateLevel = hotfixUpdateInfo.getWhiteUpdateLevel();
                        hotPackUpdateVersion = hotfixUpdateInfo.getWhiteUpdateVersion();
                    }
                }else if(forwardServer > 0){
                    if(!Objects.equals(hotfixUpdateInfo.getForwardUpdateVersion(), hotPackVersion)) {
                        hotPackUpdateLevel = hotfixUpdateInfo.getForwardUpdateLevel();
                        hotPackUpdateVersion = hotfixUpdateInfo.getForwardUpdateVersion();
                    }
                }else {
                    if(!Objects.equals(hotfixUpdateInfo.getUpdateVersion(), hotPackVersion)) {
                        hotPackUpdateLevel = hotfixUpdateInfo.getUpdateLevel();
                        hotPackUpdateVersion = hotfixUpdateInfo.getUpdateVersion();
                    }
                }
            }
        }
        resultObj.put("hotPackUpdateLevel", hotPackUpdateLevel);
        resultObj.put("isTtSs", isReview);   //是否提审
        resultObj.put("hotPackUpdateCheck", ServerListHelper.isHotPackUpdateCheck(packageVersion));   //补丁校验开关

        //如果需要更新
        if(hotPackUpdateLevel == eUpdateLevel.Suggest.getValue() || hotPackUpdateLevel == eUpdateLevel.Force.getValue()){
            //推荐更新版本信息
            resultObj.put("hotPackUpdateUrl", packageMarkData.getHotPackDownloadUrl());
            resultObj.put("hotPackUpdateVersion", hotPackUpdateVersion);
        }

        resultObj.put("forwardServer", forwardServer);
        sendMessage(response, resultObj.toJSONString());
    }

    private void oldDeal(HttpServletResponse response, String packageMark, String packageVersion, String hotPackVersion, boolean isWhiteUser,
                         int forwardServer, PackageMark packageMarkData, String language, String appId){
        //获取包体信息
        PackageVersion currVersion = PackageVersionMgr.getPackageVersion(packageMark, packageVersion);
        if(null == currVersion){
            sendMessage(response, getResultObj(GameErrorCode.E_PACKAGE_VERSION_NO_FOUND, language).toJSONString());
            logger.info("packageUpdate packageVersion no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
            return;
        }

        //获取热更包信息
        HotPackVersion currHotPackVersion = HotPackVersionMgr.getHotPackVersion(packageMark, packageVersion, hotPackVersion);
        if(null == currHotPackVersion){
            sendMessage(response, getResultObj(GameErrorCode.E_HOT_PACK_VERSION_NO_FOUND, language).toJSONString());
            logger.info("packageUpdate hotPackVersion no find, packageMark:{}, packageVersion:{}, hotPackVersion:{}", packageMark,
                    packageVersion, hotPackVersion);
            return;
        }

        //整包更新级别
        JSONObject resultObj = getResultObj(0, language);
        int updateLevel;
        if(currVersion.isDelete()){//版本标识删除表示需要强更
            updateLevel = eUpdateLevel.Force.getValue();
        }else {
            if(isWhiteUser){
                updateLevel = currVersion.getWhiteUpdateLevel();
            }else if(forwardServer > 0){
                updateLevel = currVersion.getForwardUpdateLevel();
            }else {
                updateLevel = currVersion.getUpdateLevel();
            }
        }
        resultObj.put("updateLevel", updateLevel);
        //如果需要更新
        if(updateLevel == eUpdateLevel.Suggest.getValue() || updateLevel == eUpdateLevel.Force.getValue()){
            //推荐更新版本信息
            PackageVersion updateVersion = PackageVersionMgr.getRecommendVersion(packageMark, isWhiteUser, forwardServer);
            if(null == updateVersion){
                sendMessage(response, getResultObj(GameErrorCode.E_PACKAGE_VERSION_NO_SET_RECOMMEND, language).toJSONString());
                logger.error("packageUpdate recommend packageVersion no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
                return;
            }
            //推荐更新版本信息
            if(isWhiteUser){//白名单
                resultObj.put("updateMethod", updateVersion.getWhiteUpdateMethod());
            }else if(forwardServer > 0){//先遣服
                resultObj.put("updateMethod", updateVersion.getForwardUpdateMethod());
            }else {
                resultObj.put("updateMethod", updateVersion.getUpdateMethod());
            }
            resultObj.put("updateUrl", updateVersion.getDownloadUrl());
        }

        //热更包更新级别
        int hotPackUpdateLevel;
        if(currHotPackVersion.isDelete()){//版本标识删除表示需要强更
            hotPackUpdateLevel = eUpdateLevel.Force.getValue();
        }else {
            if(isWhiteUser){
                hotPackUpdateLevel = currHotPackVersion.getWhiteUpdateLevel();
            }else if(forwardServer > 0){
                hotPackUpdateLevel = currHotPackVersion.getForwardUpdateLevel();
            }else {
                hotPackUpdateLevel = currHotPackVersion.getUpdateLevel();
            }
        }
        resultObj.put("hotPackUpdateLevel", hotPackUpdateLevel);
        boolean isReview = HotPackVersionMgr.isHotPackVersionReview(currHotPackVersion, appId, packageMarkData.getChannelId());
        resultObj.put("isTtSs", isReview);   //是否提审
        resultObj.put("hotPackUpdateCheck", currHotPackVersion.isHotPackUpdateCheck());   //补丁校验开关

        //如果需要更新
        if(hotPackUpdateLevel == eUpdateLevel.Suggest.getValue() || hotPackUpdateLevel == eUpdateLevel.Force.getValue()){
            //推荐热更版本信息
            HotPackVersion updateHotPackVersion = HotPackVersionMgr.getRecommendVersion(packageMark, packageVersion, isWhiteUser, forwardServer);
            if(null == updateHotPackVersion){
                sendMessage(response, getResultObj(GameErrorCode.E_HOT_PACK_VERSION_NO_SET_RECOMMEND, language).toJSONString());
                logger.info("packageUpdate recommend hotPackVersion no find, packageMark:{}, packageVersion:{}, hotPackVersion:{}", packageMark,
                        packageVersion, hotPackVersion);
                return;
            }
            //推荐更新版本信息
            resultObj.put("hotPackUpdateUrl", packageMarkData.getHotPackDownloadUrl());
            resultObj.put("hotPackUpdateVersion", updateHotPackVersion.getHotPackVersion());
        }

        resultObj.put("forwardServer", forwardServer);
        sendMessage(response, resultObj.toJSONString());
    }
}
